package com.google.code.syncgear.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreFailureException;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.code.syncgear.control.Dispatch;
import com.google.code.syncgear.core.Environment;

public final class DispatchServlet extends HttpServlet {

	private static final long serialVersionUID = 7139952245379632432L;
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String key = request.getParameter("key");
		if(key != null)
			if(key.trim().length() > 0)
				if(Dispatch.execute(key)) {
					DatastoreService ds = Environment.getDatastoreService();					
					Queue queue = QueueFactory.getQueue("dispatch");
					try {
					    Transaction txn = ds.beginTransaction();
					    queue.add(TaskOptions.Builder.withUrl("/dispatch").method(TaskOptions.Method.GET).countdownMillis(1000 * 60).param("key", key));
					    txn.commit();		    
					} catch (DatastoreFailureException exception) {
						throw new IOException(exception);
					}
				}
		
	}

}